package cn.com.zero.file.config;

import cn.com.zero.file.client.OSSTemplate;
import cn.com.zero.file.config.properties.FileUploadProperties;
import cn.com.zero.file.constants.FileUploadConstant;
import cn.com.zero.file.service.IFileService;
import cn.com.zero.file.service.impl.AliyunOssFileServiceImpl;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Scope;

import javax.validation.constraints.NotEmpty;

/**
 * @author liuxh
 * @version 1.0.0
 * @Description 阿里云OSS配置类
 * @createTime 2022/9/13
 */
@Configuration
@EnableConfigurationProperties({FileUploadProperties.class})
@ConditionalOnProperty(name = "zero.file.type", havingValue = FileUploadConstant.FILE_TYPE_ALIYUN)
@Import({OSSTemplate.class})
public class AliyunOSSConfig {

    @NotEmpty
    @Value("${zero.oss.endpoint}")
    private String endpoint;

    @NotEmpty
    @Value("${zero.oss.access-key}")
    private String accessKey;

    @NotEmpty
    @Value("${zero.oss.access-key-secret}")
    private String accessKeySecret;


    @NotEmpty
    @Value("${zero.oss.bucket-name}")
    private String bucketName;

    /**
     * 阿里云文件存储client
     *
     * @return oss客户端
     */
    @Bean
    @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public OSS ossClient() {
        return new OSSClientBuilder().build(endpoint, accessKey, accessKeySecret);
    }

    @Bean
    public OSSTemplate ossTemplate(FileUploadProperties fileUploadProperties) {
        return new OSSTemplate(fileUploadProperties, bucketName);
    }

    @Bean
    public IFileService fileService(OSSTemplate ossTemplate) {
        return new AliyunOssFileServiceImpl(ossTemplate);
    }


}
